package com.ql.mangersystem.service.impl;

import com.ql.mangersystem.common.ErrorCode;
import com.ql.mangersystem.common.Page;
import com.ql.mangersystem.entity.dto.*;
import com.ql.mangersystem.entity.po.User;
import com.ql.mangersystem.entity.vo.AvatarVo;
import com.ql.mangersystem.entity.vo.LoginVo;
import com.ql.mangersystem.entity.vo.PersonVo;
import com.ql.mangersystem.entity.vo.UserVo;
import com.ql.mangersystem.exception.ServiceException;
import com.ql.mangersystem.mapper.UserMapper;
import com.ql.mangersystem.service.UserService;
import com.ql.mangersystem.utils.TokenUtils;
import com.ql.mangersystem.utils.UserUtil;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;

import java.time.LocalDateTime;
import java.util.List;

import static com.ql.mangersystem.constants.RedisConstants.REDIS_CAPTCHA;
import static com.ql.mangersystem.utils.RegexUtils.isAccount;
import static com.ql.mangersystem.utils.RegexUtils.isPassword;

@Service
@Component
public class UserServiceImpl implements UserService {
    @Resource
    private UserMapper userMapper;
    @Resource
    private StringRedisTemplate stringRedisTemplate;


    @Override
    public LoginVo login(LoginDTO loginDTO) {
//        System.out.println(loginDTO);
        String userAccount = loginDTO.getUserAccount();
        String password = loginDTO.getPassword();
        String code = loginDTO.getCode();
        String captchaCode = stringRedisTemplate.opsForValue().get(REDIS_CAPTCHA + code);
        if (captchaCode == null) {
            throw new ServiceException(ErrorCode.SYSTEM_ERROR);
        }

        password = DigestUtils.md5DigestAsHex(password.getBytes());
        User user = userMapper.login(userAccount,password);
        if (user == null) {
            throw new ServiceException(400,"账户或密码错误");
        }
        String userId = String.valueOf(user.getId());
        String token = TokenUtils.genToken(userId, password);
        stringRedisTemplate.delete(REDIS_CAPTCHA + code);
        LoginVo vo = new LoginVo();
        vo.setId(user.getId());
        vo.setUsername(user.getUsername());
//        vo.setUrl(user.getAvatar());
        vo.setToken(token);
//        System.out.println(vo);
        return vo;
    }

    @Override
    public Integer register(RegisterDTO registerDTO) {
        String password = registerDTO.getPassword();
        String userAccount = registerDTO.getUserAccount();
        boolean account = isAccount(userAccount);
        if (account) {
//            return Result.error("账号格式错误");
            throw new ServiceException(ErrorCode.PARAMS_ERROR);
        }
        boolean pass = isPassword(password);
        if (pass) {
            throw new ServiceException(ErrorCode.PARAMS_ERROR);
        }

        Integer res = userMapper.isExistAccount(userAccount);
        if (res != null) {
            throw new ServiceException(4001,"账户已存在");
        }
        String checkPassword = registerDTO.getCheckPassword();
        if (!password.equals(checkPassword)) {
            throw new ServiceException(ErrorCode.PARAMS_ERROR);
        }
        LocalDateTime createTime = LocalDateTime.now();
        LocalDateTime updateTime = LocalDateTime.now();
        String username = UserUtil.generateUniqueUsername();
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        return userMapper.register(userAccount,password,username,createTime,updateTime);
    }

    @Override
    public User selectById(Integer id) {
        return userMapper.selectById(id);
    }

//    @Override
//    public Result selectById(Integer id) {
//        User user = userMapper.selectById(id);
//        return Result.success(user);
//    }

    @Override
    public PersonVo getById(Integer id) {

        return userMapper.getById(id);
    }

    @Override
    public AvatarVo getAvatar(Integer id) {
        return userMapper.getAvatar(id);
    }

    @Override
    public int edit(PersonDTO personDTO) {
        String avatar = personDTO.getAvatar();
        String name = personDTO.getName();
        String phone = personDTO.getPhone();
        String email = personDTO.getEmail();
        Integer gender = personDTO.getGender();
        String address = personDTO.getAddress();
        Integer userId = personDTO.getUserId();
        LocalDateTime now = LocalDateTime.now();
        return userMapper.edit(address,avatar,name,phone,email,gender,userId,now);
    }

    @Override
    public int changePassword(PasswordDTO passwordDTO) {
        String newPassword = passwordDTO.getNewPassword();
        String oldPassword = passwordDTO.getOldPassword();
        Integer userId = passwordDTO.getUserId();
        User user = userMapper.selectById(userId);
        boolean pass = isPassword(oldPassword);
        boolean password = isPassword(newPassword);
        if (pass&& password) {
            throw new ServiceException(ErrorCode.PARAMS_ERROR);
        }
        oldPassword = DigestUtils.md5DigestAsHex(oldPassword.getBytes());
        newPassword = DigestUtils.md5DigestAsHex(newPassword.getBytes());
//        System.out.println(!user.getPassword().equals(oldPassword));
        if (!user.getPassword().equals(oldPassword)) {
            throw new ServiceException(400,"旧密码不正确");
//            return Result.error("旧密码不正确")
        }
        return userMapper.changePassword(newPassword,userId);
    }

    @Override
    public int forgetPassword(ForgetDTO forgetDTO) {
        String password = forgetDTO.getPassword();
        String checkPassword = forgetDTO.getCheckPassword();
        String phone = forgetDTO.getPhone();
        String name = forgetDTO.getName();
        boolean pass = isPassword(password);
        boolean pas = isPassword(checkPassword);
        if (pass&& pas) {
            throw new ServiceException(400,"密码格式错误");
        }
        if (!password.equals(checkPassword)) {
            throw new ServiceException(400,"两次密码不一致");
        }
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        return userMapper.forgetPassword(password,phone,name);
    }

    @Override
    public Page<UserVo> page(UserPageDTO userPageDTO) {
        Integer pageNum = userPageDTO.getPageNum();
        Integer pageSize = userPageDTO.getPageSize();
        Integer skipNum = (pageNum - 1) * pageSize;
        Page<UserVo> page = new Page<>();
        Integer total = userMapper.countId();
        List<UserVo> list = userMapper.list(skipNum,pageSize);
        page.setList(list);
        page.setTotal(total);
        return page;
    }

    @Override
    public List<UserVo> export() {
        return userMapper.export();
    }

    @Override
    public void saveBatch(List<User> userList) {
        userMapper.saveBatch(userList);
    }

    @Override
    public User getUserById(Integer userid) {
        return userMapper.getByUserId(userid);
    }

    /**
     * 根据账户查询用户名
     */
    @Override
    public String selectByAccount(String userAccount) {
        return userMapper.selectByAccount(userAccount);
    }

//    @Override
//    public Integer count(String userAccount) {
//        return userMapper.count(userAccount);
//    }
}
